package com.fsh.club.gateway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 作者：fsh
 * 日期：2023/11/30
 * <p>
 * 描述：授权过滤器。  认证解析token ，获取loginId ，放到header里，发给各个微服务
 * GlobalFilter是Spring Cloud Gateway中定义的接口，用于定义全局的过滤器。
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {

    @Override
    @SneakyThrows
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        //获取请求到网关的地址
        String path = request.getURI().getPath();
        if(log.isInfoEnabled()){
            log.info("AuthorizeFilter.class-filter()-请求的路径是：{}",path);
        }
        //如果是登录，那就通过
//        if("/auth/user/doLogin".equals(path)){
//            mutate.header("loginId","ox1lI6pkOLMzKdrtdmyjLHFxqevA");
//            return chain.filter(exchange.mutate().request(mutate.build()).build());
////            return chain.filter(exchange);
//        }
        if(path.contains("doLogin")){
            mutate.header("loginId","ox1lI6pkOLMzKdrtdmyjLHFxqevA");
            return chain.filter(exchange.mutate().request(mutate.build()).build());
        }

        //其他请求路径，就要携带 loginId 转发给各个微服务
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String loginId = (String)tokenInfo.getLoginId();
        if(StringUtils.isBlank(loginId)){
            throw new Exception("未能获取到有效信息");
        }
        //封装到 header中 , 重写request请求发送
        mutate.header("loginId",loginId);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
